package com.bjpowernode.crm.workbench.web.controller;

import com.bjpowernode.crm.commons.constants.Constant;
import com.bjpowernode.crm.commons.domain.ReturnObject;
import com.bjpowernode.crm.commons.utils.DateUtils;
import com.bjpowernode.crm.commons.utils.UUIDUtils;
import com.bjpowernode.crm.settings.domain.DicValue;
import com.bjpowernode.crm.settings.domain.User;
import com.bjpowernode.crm.settings.service.DicValueService;
import com.bjpowernode.crm.settings.service.UserService;
import com.bjpowernode.crm.workbench.domain.Activity;
import com.bjpowernode.crm.workbench.domain.Clue;
import com.bjpowernode.crm.workbench.domain.ClueActivityRelation;
import com.bjpowernode.crm.workbench.domain.ClueRemark;
import com.bjpowernode.crm.workbench.service.ActivityService;
import com.bjpowernode.crm.workbench.service.ClueActivityRelationService;
import com.bjpowernode.crm.workbench.service.ClueRemarkService;
import com.bjpowernode.crm.workbench.service.ClueService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.*;

@Controller
public class ClueController {

    @Autowired
    private UserService userService;
    @Autowired
    private DicValueService dicValueService;
    @Autowired
    private ClueService clueService;
    @Autowired
    private ClueRemarkService clueRemarkService;
    @Autowired
    private ActivityService activityService;
    @Autowired
    private ClueActivityRelationService clueActivityRelationService;

    @RequestMapping("/workbench/clue/index.do")
    public String index(HttpServletRequest request) {
        //调用service
        List<User> userList = userService.queryAllUser();
        List<DicValue> appellationList = dicValueService.queryDicValueByDataType("appellation");
        List<DicValue> clueStateList = dicValueService.queryDicValueByDataType("clueState");
        List<DicValue> sourceList = dicValueService.queryDicValueByDataType("source");
        //将数据传到request域中
        request.setAttribute("userList", userList);
        request.setAttribute("appellationList", appellationList);
        request.setAttribute("clueStateList", clueStateList);
        request.setAttribute("sourceList", sourceList);
        return "workbench/clue/index";
    }

    @RequestMapping("/workbench/clue/saveCreateClue.do")
    @ResponseBody
    public Object saveCreateClue(Clue clue, HttpSession session) {
        User user = (User) session.getAttribute(Constant.SESSION_USER);
        //封装参数
        clue.setId(UUIDUtils.getUUID());
        clue.setCreateBy(user.getId());
        clue.setCreateTime(DateUtils.formateDataTime(new Date()));

        ReturnObject returnObject = new ReturnObject();
        //调用Service方法
        try {
            int result = clueService.saveCreateClue(clue);
            if (result > 0) {
                returnObject.setCode(Constant.RETURN_CODE_SUCCESS);
            } else {
                //失败
                returnObject.setCode(Constant.RETURN_CODE_FAIL);
                returnObject.setMessage("网络开小差去了，请稍后再试...");
            }
        } catch (Exception e) {
            e.printStackTrace();
            returnObject.setCode(Constant.RETURN_CODE_FAIL);
            returnObject.setMessage("网络开小差去了，请稍后再试...");

        }
        return returnObject;
    }

    @RequestMapping("/workbench/clue/queryAllClues.do")
    @ResponseBody
    public Object queryAllClues(String fullname, String company, String phone, String mphone, String source, String owner, String state,
                                int pageNo, int pageSize) {
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("fullname", fullname);
        map.put("company", company);
        map.put("phone", phone);
        map.put("mphone", mphone);
        map.put("source", source);
        map.put("owner", owner);
        map.put("state", state);
        map.put("beginNo", (pageNo - 1) * pageSize);
        map.put("pageSize", pageSize);

        //调用Service
        List<Clue> clueList = clueService.queryClueByConditionForPage(map);
        int totalRows = clueService.queryCountOfClueByCondition(map);

        //这里再次使用map封装数据是为了将数据传输给前端，在map中的数据会以xx-xx的形式传递这些参数，和json格式一致
        Map<String, Object> resultMap = new HashMap<String, Object>();
        resultMap.put("clueList", clueList);
        resultMap.put("totalRows", totalRows);

        return resultMap;
    }

    @RequestMapping("/workbench/clue/queryClueById.do")
    @ResponseBody
    public Object queryClueById(String id) {
        return clueService.queryClueById(id);
    }

    @RequestMapping("/workbench/clue/saveUpdateClueById.do")
    @ResponseBody
    public Object saveUpdateClueById(Clue clue, HttpSession session) {
        //封装参数
        clue.setEditTime(DateUtils.formateDataTime(new Date()));//修改时间

        User user = (User) session.getAttribute(Constant.SESSION_USER);
        clue.setEditBy(user.getId());//修改者

        ReturnObject returnObject = new ReturnObject();

        try {
            int result = clueService.updateClueById(clue);
            if (result > 0) {
                returnObject.setCode(Constant.RETURN_CODE_SUCCESS);
            } else {
                //失败
                returnObject.setCode(Constant.RETURN_CODE_FAIL);
                returnObject.setMessage("网络开小差去了，请稍后再试...");
            }
        } catch (Exception e) {
            e.printStackTrace();
            returnObject.setCode(Constant.RETURN_CODE_FAIL);
            returnObject.setMessage("网络开小差去了，请稍后再试...");

        }
        return returnObject;
    }

    @RequestMapping("/workbench/clue/deleteClueById.do")
    @ResponseBody
    public Object deleteCluesById(String[] id) {
        ReturnObject returnObject = new ReturnObject();
        try {
            int i = clueService.deleteClueById(id);
            if (i != 0) {
                returnObject.setCode(Constant.RETURN_CODE_SUCCESS);
            } else {
                returnObject.setCode(Constant.RETURN_CODE_FAIL);
                returnObject.setMessage("系统忙请稍后重试！");
            }
        } catch (Exception e) {
            e.printStackTrace();
            returnObject.setCode(Constant.RETURN_CODE_FAIL);
            returnObject.setMessage("系统忙请稍后重试！");
        }
        return returnObject;
    }

    @RequestMapping("/workbench/detail/queryClueRemarkByClueId.do")
    public String queryClueRemarkByClueId(String id, HttpServletRequest request) {
        //1.clue表的详细信息
        Clue clue = clueService.queryClueDetailById(id);
        //2.clue表的备注信息
        List<ClueRemark> clueRemarkList = clueRemarkService.queryClueRemarkByClueId(id);
        //3.clue表与activity表的关联信息
        List<Activity> activityList = activityService.queryActivityByClueId(id);

        request.setAttribute("clue", clue);
        request.setAttribute("clueRemarkList", clueRemarkList);
        request.setAttribute("activityList", activityList);

        return "workbench/clue/detail";
    }

    @RequestMapping("/workbench/clue/queryActivityForDetailByNameClueId.do")
    @ResponseBody
    public Object queryActivityForDetailByNameClueId(String activityName, String clueId) {
        //封装参数
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("activityName", activityName);
        map.put("clueId", clueId);
        //调用service层方法，查询市场活动
        List<Activity> activityList = activityService.queryActivityByNameAndClueId(map);
        //根据查询结果，返回响应信息
        return activityList;
    }

    /**
     * 保存关系
     *
     * @param activityId
     * @param clueId
     * @return
     */
    @RequestMapping("workbench/clue/saveBund.do")
    @ResponseBody
    public Object saveBund(String[] activityId, String clueId) {
        ClueActivityRelation car = null;
        //封装参数
        List<ClueActivityRelation> relationList = new ArrayList<ClueActivityRelation>();
        for (String ai : activityId) {
            car = new ClueActivityRelation();
            car.setActivityId(ai);
            car.setClueId(clueId);
            car.setId(UUIDUtils.getUUID());
            relationList.add(car);
        }
        ReturnObject returnObject = new ReturnObject();

        //调用Service方法
        try {
            int result = clueActivityRelationService.saveActivityClueRelation(relationList);
            if (result > 0) {
                returnObject.setCode(Constant.RETURN_CODE_SUCCESS);
                //如果保存成功，就调用ActivityService查询市场活动,并返回数据
                List<Activity> activityList = activityService.queryActivityById(activityId);
                returnObject.setRetData(activityList);
            } else {
                returnObject.setCode(Constant.RETURN_CODE_FAIL);
                returnObject.setMessage("系统忙请稍后重试！");
            }
        } catch (Exception e) {
            e.printStackTrace();
            returnObject.setCode(Constant.RETURN_CODE_FAIL);
            returnObject.setMessage("系统忙请稍后重试！");
        }
        return returnObject;
    }

    /**
     * 删除关系
     *
     * @param relation
     * @return
     */
    @RequestMapping("/workbench/clue/deleteClueActivityRelation.do")
    @ResponseBody
    public Object deleteClueActivityRelation(ClueActivityRelation relation) {
        ReturnObject returnObject = new ReturnObject();

        try {
            int result = clueActivityRelationService.deleteActivityClueRelation(relation);
            if (result > 0) {
                returnObject.setCode(Constant.RETURN_CODE_SUCCESS);
            } else {
                returnObject.setCode(Constant.RETURN_CODE_FAIL);
                returnObject.setMessage("系统忙请稍后重试！");
            }
        } catch (Exception e) {
            e.printStackTrace();
            returnObject.setCode(Constant.RETURN_CODE_FAIL);
            returnObject.setMessage("系统忙请稍后重试！");
        }
        return returnObject;
    }

    /**
     * 这是是实现线索转换功能，由于需要的是clue表的信息，对应的mapper和service都有，就直接复用了
     *
     * @param id
     * @return
     */
    @RequestMapping("/workbench/convert/convertIndex.do")
    public String convertIndex(String id, HttpServletRequest request) {
        //封装参数
        Clue clue = clueService.queryClueDetailById(id);
        List<DicValue> stageList = dicValueService.queryDicValueByDataType("stage");
        //保存到request域中
        request.setAttribute("clue", clue);
        request.setAttribute("stageList", stageList);

        //请求转发到页面
        return "workbench/clue/convert";
    }

    @RequestMapping("/workbench/convert/queryActivityConvertByActivityNameAndClueId.do")
    @ResponseBody
    public Object queryActivityConvertByActivityNameAndClueId(String activityName, String clueId) {
        //封装参数
        Map<String,Object> map = new HashMap<String, Object>();
        map.put("activityName",activityName);
        map.put("clueId",clueId);

        //调用Service
        List<Activity> activityList = activityService.queryActivityConvertForActivityNameAndClueId(map);

        //返回响应信息
        return activityList;
    }

    @RequestMapping("/workbench/clue/saveConvertClue.do")
    @ResponseBody
    public Object saveConvertClue(String clueId,String money,String name,String expectedDate,
                              String stage,String activityId,String isCreateTran,HttpSession session){
        Map<String,Object> map = new HashMap<String, Object>();
        map.put("clueId",clueId);
        map.put("money",money);
        map.put("name",name);
        map.put("expectedDate",expectedDate);
        map.put("stage",stage);
        map.put("activityId",activityId);
        map.put("isCreateTran",isCreateTran);
        map.put(Constant.SESSION_USER,session.getAttribute(Constant.SESSION_USER));
        ReturnObject returnObject = new ReturnObject();
        try {
            clueService.saveClueAboutCompany(map);
            returnObject.setCode(Constant.RETURN_CODE_SUCCESS);
        } catch (Exception e) {
            e.printStackTrace();
            returnObject.setCode(Constant.RETURN_CODE_FAIL);
            returnObject.setMessage("系统忙，请稍后重试...");
        }
        return returnObject;
    }
}
